<template>
  <a-config-provider
    :locale="locale == 'zh_CN' ? zhCN : enUS"
    :theme="{
      token: {
        colorPrimary: nowCustomColor ? nowCustomColor : nowTheme === 'dark' ? '#646cff' : '#1677ff',
      },
      algorithm: nowTheme === 'dark' ? anttheme.darkAlgorithm : anttheme.defaultAlgorithm,
    }"
  >
    <router-view v-slot="{ Component, route }" :key="$route.fullPath">
      <!-- <keep-alive :include="storeVuex.state.keepAliveCache"> -->
      <keep-alive v-if="$route.meta.keepAlive">
        <component :is="Component" :key="$route.path" />
      </keep-alive>
      <component :is="Component" v-else :key="$route.path" />
    </router-view>
  </a-config-provider>
</template>

<script lang="ts" setup>
defineOptions({ name: 'App' });
import { theme as anttheme } from 'ant-design-vue';

import zhCN from 'ant-design-vue/es/locale/zh_CN';
import enUS from 'ant-design-vue/es/locale/en_US';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');

import { useI18n } from 'vue-i18n';
const i18n = useI18n({ useScope: 'global' });

import useCommonStore from '/@/store/modules/common';
import { storeToRefs } from 'pinia';
let pinia = useCommonStore();
let { locale, theme, customColor } = storeToRefs(pinia);
// 下面这样写，多写个watch监听和storage监听，是为了兼容多窗口切换主题，一点都不多余
const nowTheme = ref(theme.value);
const nowCustomColor = ref(customColor.value);
// 监听当前窗口的主题变化
watch(theme, (val) => {
  nowTheme.value = val;
});
watch(customColor, (val) => {
  nowCustomColor.value = val;
});
// 多窗口监听 监听storage 改变其他窗口主题，语言变化
window.addEventListener('storage', function (e) {
  console.log('e.key ', e.key);
  if (e.key === 'common') {
    let storage = JSON.parse(e.newValue || '{}');
    nowTheme.value = storage.theme;
    console.log('storage', storage);
    init(storage.theme, storage.locale);
    pinia.changeTheme(storage.theme);
    pinia.changeLocal(storage.locale);
    pinia.changeCustomColor(storage.customColor);
  }
});
const changeElementClass = (isDark: boolean) => {
  if (isDark) {
    document.documentElement.removeAttribute('class');
    document.documentElement.setAttribute('class', 'dark');
  } else {
    document.documentElement.removeAttribute('class');
    document.documentElement.setAttribute('class', 'light');
  }
};
const init = (theme: string, locale: string) => {
  // theme
  document.documentElement.setAttribute('style', `color-scheme: ${theme}`);
  changeElementClass(theme == 'dark');
  // locale
  i18n.locale.value = locale;
};
init(pinia.$state.theme, pinia.$state.locale);
</script>
